import { defineStore } from "pinia";
import { getToken, removeToken, setToken } from "../utils/token-utils";
import { ElMessage } from "element-plus";
import { staticRoutes } from "@/router/routes";
import userApi, {
  type LoginParamsData,
  type UserInfoData,
} from "@/api/userInfo";
import type { RouteRecordRaw } from "vue-router";
// import type {LoginParamsData} from '@/api/userInfo'

type UserinfoStateData = {
  token: string;
  userInfo: UserInfoData;
  menuRoutes: RouteRecordRaw[];
};

// 封装函数 初始化userInfo数据
function initUserinfo() {
  return {
    routes: [],
    buttons: [],
    roles: [],
    name: "",
    avatar: "",
  };
}

export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserinfoStateData => ({
    token: localStorage.getItem("token") || "",
    userInfo: initUserinfo(),
    menuRoutes: staticRoutes, //这个数组(路由数组)来去生成每一个菜单选项 菜单是根据路由动态生成的
  }),

  actions: {
    async login(loginParams: LoginParamsData) {
      try {
        const res = await userApi.login(loginParams);
        this.token = res.token;
        localStorage.setItem("token", res.token);
        return "ok";
      } catch (error) {
        return Promise.reject("fail");
      }
    },

    async getInfo() {
      try {
        const res = await userApi.info();
        this.userInfo = res;
        return "ok";
      } catch (error) {
        return Promise.reject("fail");
      }
    },

    // 重置用户相关的信息  退出登录以及token过期
    reset() {
      this.token = "";
      localStorage.removeItem("token");
      // this.userInfo = {};
      this.userInfo = Object.assign(this.userInfo,initUserinfo()) //清空userInfo
    },

    async logout() {
      try {
        const res = await userApi.logout();
        // 清除用户相关信息
        this.reset();
        return "ok";
      } catch (error) {
        return Promise.reject("fail");
      }
    },
  },
});
